var Promise = require('bluebird');
var ObjectID = require('mongodb').ObjectID;
var cheerio = require('cheerio');

var mongoBase = require('../common/mongo-base');
var page = require('../common/page');
var utils = require('../common/utils');

module.exports = {
  newsList: newsList,
  newsListHasPhoto: newsListHasPhoto,
  showArticle: showArticle,
  saveArticle: saveArticle,
  updateArticle: updateArticle,
  removeArticle: removeArticle
};

function newsList(req, res, next) {

  var pageNo = Math.floor(req.query.pageNo);
  var pageSize = Math.floor(req.query.pageSize);
  pageNo = pageNo ? pageNo: 1;
  pageSize = pageSize ? pageSize: 20;

  var query = {};

  var fields = {_id:1,  artibodyTitle:1, mediaName:1, pubDate:1, medialink:1};
  var options = {sort:{date:-1}, skip: (pageNo - 1) * pageSize, limit:pageSize};

  Promise.all([
    mongoBase.findData('news-article', query, fields, options),
    mongoBase.countData('news-article')
  ])

  .then(function(results) {
    var resData = {
      type: 'news',
      title: '航空资讯列表',
      searchUrl: '/admin/newsEditSearch',
      showUrl: '/admin/showNewsArticle',
      removeUrl: '/admin/removeNewsArticle',
      pageUrl: '/admin/newsArticleList',
      list: results[0],
      totalCount: results[1]
    }
    /*分页数据*/
    resData.page = page.getPage(pageNo, pageSize, resData.totalCount, 7);

    res.render('admin/article-edit-list', resData);
  })

  .catch(function(err){
    console.log(err);
  });
}

function newsListHasPhoto(req, res, next) {

  var chooseLink = req.query.chooseLink;
  var parentId = req.query.parentId;

  var pageNo = Math.floor(req.query.pageNo);
  var pageSize = Math.floor(req.query.pageSize);
  pageNo = pageNo ? pageNo: 1;
  pageSize = pageSize ? pageSize: 20;

  var query = {hisPhoto: true};
  var fields = {_id:1,  artibodyTitle:1, mediaName:1, pubDate:1, medialink:1};
  var options = {sort:{date:-1}};

 mongoBase.findData('news-article', query, fields, options)

  .then(function(data) {
    var newsList = utils.getSearchlist(data, pageNo, pageSize);

    var resData = {
      type: 'news',
      title: '航空资讯列表',
      searchUrl: '/admin/newsChooseSearch',
      pageUrl: '/admin/newsListHasPhoto',
      list: newsList,
      totalCount: data.length,
      chooseLink: chooseLink
    }
    if(parentId) {
      resData.parentId = parentId;
    }
    /*分页数据*/
    resData.page = page.getPage(pageNo, pageSize, resData.totalCount, 7);

    res.render('admin/article-choose-list', resData);
  })

  .catch(function(err){
    console.log(err);
  });
}


function showArticle(req, res, next) {
  var artId = req.query.artId;
  if(!artId) {
    res.render('admin/article-edit', {title: '新增资讯文章'});
    return;
  }

  var query = {_id: new ObjectID(artId)};
  var fields = {_id:1, artibodyTitle:1, mediaName:1, medialink:1, photo:1, pubDate:1, keywords:1, artibody:1};

  mongoBase.findOneData('news-article', query, fields)

    .then(function(data) {

      var resData = {
        title: '编辑资讯文章',
        articles: data
      };
       res.render('admin/article-edit', resData);
    })

    .catch(function(err){
      console.log(err);
    });
}

function saveArticle(req, res, next) {
  var artibodyTitle = req.body.artibodyTitle;
  var mediaName = req.body.mediaName;
  var medialink = req.body.medialink;
  var photo = req.body.photo;
  var pubDate = req.body.pubDate;
  var keywords = req.body['keywords[]'];
  var artibody = req.body.artibody;

  if(!artibodyTitle || !artibody) {
    next();
    return ;
  }
  var date = new Date()
  if(pubDate) {
    date = new Date(Date.parse(pubDate.replace('年','-').replace('月','-').replace('日','')));
  } else {
    pubDate = date.getFullYear() + '年' + (Math.floor(date.getMonth())+1) + '月' + date.getDate() + '日' +
     ' ' + date.getHours() + ':' + date.getMinutes();
  }
  var ellipsis = '';
  var $ = cheerio.load(artibody);
  $('p').each(function(idx, dom) {
    if(idx < 3) {
      ellipsis +=  $(dom).html() + '<br/>'
    } else {
      return ;
    }
  });
  if(!ellipsis) {
    ellipsis = artibody;
  }


  var articleData = {
    artibodyTitle: artibodyTitle,
    mediaName: mediaName,
    medialink: medialink,
    photo: photo,
    pubDate: pubDate,
    keywords: keywords,
    artibody: artibody,
    ellipsis: ellipsis,
    date: date,
  };
  articleData.hisPhoto = articleData.photo ? true : false;

  mongoBase.saveData('news-article', articleData)
    
    .then(function() {

      newsList(req, res, next);

    })

    .catch(function(err){
      console.log(err);
    });
}

function updateArticle(req, res, next) {
  var artId = req.body.artId;
  
  var artibodyTitle = req.body.artibodyTitle;
  var mediaName = req.body.mediaName;
  var medialink = req.body.medialink;
  var photo = req.body.photo;
  var pubDate = req.body.pubDate;
  var keywords = req.body['keywords[]'];
  var artibody = req.body.artibody;

  if(!artibodyTitle || !artibody) {
    next();
    return ;
  }
  var date = new Date()
  if(pubDate) {
    date = new Date(Date.parse(pubDate.replace('年','-').replace('月','-').replace('日','')));
  } else {
    pubDate = date.getFullYear() + '年' + (Math.floor(date.getMonth())+1) + '月' + date.getDate() + '日' +
     ' ' + date.getHours() + ':' + date.getMinutes();
  }
  var ellipsis = '';
  var $ = cheerio.load(artibody);
  $('p').each(function(idx, dom) {
    if(idx < 3) {
      ellipsis +=  $(dom).html() + '<br/>'
    } else {
      return ;
    }
  });
  if(!ellipsis) {
    ellipsis = artibody;
  }


  var articleData = {
    artibodyTitle: artibodyTitle,
    mediaName: mediaName,
    medialink: medialink,
    photo: photo,
    pubDate: pubDate,
    keywords: keywords,
    artibody: artibody,
    ellipsis: ellipsis,
    date: date,
  };
  articleData.hisPhoto = articleData.photo ? true : false;

  var query = {_id: new ObjectID(artId)};

  mongoBase.updateData('news-article', query, articleData)
    
    .then(function(data) {

      newsList(req, res, next);

    })

    .catch(function(err){
      console.log(err);
    });
}


function removeArticle(req, res, next) {
  
  var artId = req.query.artId;

  var query = {_id: new ObjectID(artId)};

  mongoBase.removeData('news-article', query)

    .then(function() {

      newsList(req, res, next);

    })

    .catch(function(err){
      console.log(err);
    });
}

